// pages/add/add.js
import { formatTime } from '../../utils/util'
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: "",
    fileList: [],
    isLogin: wx.getStorageSync('isLogin')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },
  afterRead(e){
    console.log(e)
    this.setData({ fileList: [...this.data.fileList, ...e.detail.file] })
  },
  ondelete(e){
    let fileList = this.data.fileList
    fileList.splice(e.detail,1)
    this.setData({ fileList })
  },
  async onsumbit(){
    let content = this.data.content
    if(!content){
      wx.showToast({
        title: '必须填写内容！',
        icon: 'none'
      })
      return
    }
    let fileList = await this.uploadToCloud()
    if (!fileList) {
      return
    } 
    console.log(fileList)
    
    let location = wx.getStorageSync('location')
    await db.collection('article').add({
      data: {
        content,
        fileList,
        userInfo: wx.getStorageSync('userInfo'),
        createDate: formatTime(new Date()),
        location: {
          type: 'Point',
          coordinates: [location.longitude, location.latitude]
        }
      }
    })
    wx.showToast({
      title: '发布成功',
    })
    setTimeout(()=>{
      wx.navigateBack()
    },1500)
  },
  // 上传图片
  uploadToCloud() {
    wx.cloud.init();
    const {
      fileList
    } = this.data;
    if (!fileList.length) {
      wx.showToast({
        title: '请选择图片',
        icon: 'none'
      });
      return
    } else {
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`my-photo${new Date().getTime()}.png`, file));
      return Promise.all(uploadTasks)
    }
  },

  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.path
    });
  },
  getuserinfo(e){
    console.log(e)
    let data = e.detail
    if(data.errMsg === "getUserInfo:ok"){
      wx.setStorageSync('userInfo', data.userInfo)
      wx.setStorageSync('isLogin', true)
      this.setData({ isLogin: true })
      this.onsumbit()
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})